const express = require('express');
const jwt = require("jsonwebtoken");

const userDao=require('../database/UserDao');
const cfg = require('../config/config');

const router = express.Router();

router.post("/reg",async(req,res)=>{
    try{
        let {name,pwd} = req.body;//从请求头中获取用户名和密码
        if(await userDao.selectByName(name)){
            res.send({code:4000,msg:"用户名已存在",data:null});
        }
        else{
            let result = await userDao.registerUser(name,pwd);
            console.log("/Users注册的结果/reg是:\n" +JSON.stringify(result) + "\n————\n");
            res.send({code:2000,msg:"注册成功",data:null});
        }
        
    }catch(err){
        res.send({code:5000,msg:"注册失败",data:null});
    }
})

router.post("/login",async(req,res)=>{
    let {name,pwd} = req.body;
    try{    
        let user = await userDao.loginUser(name,pwd);
        // console.log(rows);
        if(user){
            user.user_pwd = null;
            let jwttoken = jwt.sign(user, cfg.jwtSecret, {expiresIn:"1h"});
            console.log("/Users登录的结果/login是:\n" +JSON.stringify(user) + "\n————\n");
            res.send({code:2000,msg:"登录成功",data:{user,jwttoken}});
        }else{
            res.send({code:4000,msg:"登录失败",data:null});
        }
    }catch(err){
        console.log(err);
        res.send({code:5000,msg:"服务器错误",data:err});
    }
})

router.get("/:userID",async(req,res)=>{
    let userID = req.params.userID;
    console.log("在users的get/:userID里的userID:"+userID);
    try{
        let result = await userDao.selectById(userID);
        console.log("/Users查询的结果/:userID是:\n" +JSON.stringify(result) + "\n————\n");
        res.send({code:2000,msg:"查询成功",data:result});
    }
    catch(err){
        console.log(err);
        res.send({code:5000,msg:"服务器错误",data:err});
    }
})

router.put("/:GroupID",async(req,res)=>{
    let {GroupID} = req.params;
    let user = req.user;
    try{
        let result = await userDao.updataUserSelectedGroupID(user.user_id,GroupID);
        console.log("/Users修改的结果/:GroupID是:\n" +JSON.stringify(result) + "\n————\n");
        res.send({code:2000,msg:"修改成功",data:result});
    }catch(err){
        console.log(err);
        res.send({code:5000,msg:"服务器错误",data:err});
    }
})

module.exports = router;